<template>
	<view class="flex flex-col h-screen">
		<NavBarVue title="帖子详情"></NavBarVue>
		<view class="like" @click="Like()">
			<uni-icons type="heart" v-if="_like" color="#f00" size="50rpx"></uni-icons>
			<uni-icons type="heart" v-else size="50rpx"></uni-icons>
		</view>
		<view class="flex-1 overflow-hidden">
			<scroll-view scroll-y="true" class="h-full">
				<view class="px-30" v-if="!loading">
					<view class="rounded-lg bg-white p-20">
						<postCompVue :post="postDetail" :type="2"></postCompVue>
						<view class="line mt-20" v-if="postDetail.aanlist?.length || postDetail.manlist?.length"></view>
						<view v-if="postDetail.aanlist?.length">
							<unscrambleCompVue v-for="(item, idx) in postDetail.aanlist" :key="idx" :post="item" :userType="1"
								:obs="postDetail.obs" @upDateData="getDetail()"></unscrambleCompVue>
						</view>
						<view v-if="postDetail.manlist?.length">
							<unscrambleCompVue v-for="(item, idx) in postDetail.manlist" :key="idx" :post="item" :userType="2"
								:obs="postDetail.obs" @upDateData="getDetail()"></unscrambleCompVue>
						</view>
					</view>
				</view>
				<view class="btn-unscramble" @click="handleGoEnd" v-if="postDetail.sts == 1 && isSelf">
					<view class="flex mt-20 pl-40 text-white font-bold text-sm">结算订单</view>
				</view>
				<view class="btn-unscramble" @click="onReply" v-if="isUnscramble">
					<view class="flex mt-20 pl-40 text-white font-bold text-sm">我来解读</view>
				</view>
			</scroll-view>
		</view>
		<uni-popup ref="confirmDialogRef" type="dialog">
			<uni-popup-dialog type="warn" cancelText="否" confirmText="是" title="提示" content="确定要提前结算吗？"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="popupChooseRef" type="center" @maskClick="handleMaskClick">
			<view class="bg-white rounded-lg p-30 mx-30 pb-0">
				<view class="text-center text-lg font-bold text-[#666666]">请选择打赏</view>
				<scroll-view scroll-y="true" class="h-[70vh]">
					<unscrambleCompVue v-model="chooseList" v-for="(item, idx) in postDetail.manlist" :key="idx" :post="item"
						:userType="2" :multiple="true"></unscrambleCompVue>
				</scroll-view>
				<view class="flex items-center py-30">
					<view class="flex-1 p-20 bg-[#DDE1E3] text-center rounded-l-md text-[#333333]" @click="handleNowSubmit">不，直接结算
					</view>
					<view class="flex-1 p-20 bg-[#329EFF] text-center rounded-r-md text-white" @click="handleSubmit">打赏结算</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		onLoad,
		onShow,
	} from "@dcloudio/uni-app"
	import communityApi from '@/apis/apiList/communityApi';
	import postCompVue from '@/components/postComp.vue';
	import unscrambleCompVue from '@/components/unscrambleComp.vue';
	import config from '../../config/index.js'

	const postId = ref("") // 帖子ID
	const postDetail = ref({}) // 帖子详情
	const popupRef = ref(null)
	const confirmDialogRef = ref(null)
	const popupChooseRef = ref(null)
	const aanList = ref([]) // 主播解读列表
	const manList = ref([]) // 用户（游客）解读列表
	const chooseList = ref([]) // 已选择用户（游客）解读列表
	const loading = ref(false) // 加载中
	const isAch = ref(0)
	const _like = ref(false)

	const aanLen = computed(() => { // 已解读人数
		if (postDetail.value.aanlist) {
			return postDetail.value.aanlist.length
		} else {
			return 0
		}
	})

	const maxLen = computed(() => { // 最大解读人数
		return postDetail.value.pret
	})

	const chooseLen = computed(() => { // 可选解读人数
		return parseInt(maxLen.value - aanLen.value)
	})

	const isSelf = computed(() => { // 是否是发帖人
		const userId = uni.getStorageSync('user').id
		if (userId == postDetail.value.member.id) {
			return true
		} else {
			return false
		}
	})

	const isUnscramble = computed(() => { // 是否可以解读
		const isAch = uni.getStorageSync('user').ach
		if (isAch == 1 && postDetail.value.sts == 0 && !isSelf.value) {
			return true
		} else if (isAch == 0 && postDetail.value.sts == 0 && !isSelf.value && postDetail.value.exp == 1) {
			return true
		} else {
			return false
		}
	})

	onLoad((option) => {
		postId.value = option.id;
		loading.value = true
		isAch.value = uni.getStorageSync('user').ach
	})

	onShow((option) => {
		getDetail()
	})

	const handleNowSubmit = () => {
		const opt = {
			id: postId.value,
			memberids: []
		}
		communityApi.settleMentpossend(opt).then(res => {
			popupChooseRef.value.close()
			getDetail()
		})
	}

	const handleSubmit = () => {
		if ((chooseLen.value) > chooseList.value.length) {
			const opt = {
				id: postId.value,
				memberids: chooseList.value
			}
			console.log(opt)
			// return
			communityApi.settleMentpossend(opt).then(res => {
				popupChooseRef.value.close()
				getDetail()
			})
		} else {
			uni.showToast({
				icon: 'none',
				title: `最多只能选择${chooseLen.value}人打赏！`
			})
		}
	}

	const handleMaskClick = () => {
		chooseList.value = []
	}

	const handleGoEnd = () => {
		// console.log(aanLen.value, maxLen.value)
		if (postDetail.value.manList?.length) {
			confirmDialogRef.value.open()
		}
	}

	const dialogConfirm = () => {
		if (aanLen.value < maxLen.value) {
			// 弹窗选择有空解读
			popupChooseRef.value.open()
		} else if (aanLen.value == maxLen.value) {
			// 调用结算接口
		}
		confirmDialogRef.value.close()
	}

	const dialogClose = () => {
		confirmDialogRef.value.close()
	}

	const getDetail = () => {
		const opt = {
			id: postId.value,
			'member.id': uni.getStorageSync('user').id
		}
		loading.value = true
		communityApi.getPossInfobyPossid(opt).then(res => {
			if (res.data.aanlist) {
				res.data.aanlist.map(post => {
					if (post.sts == 1) {
						let arr = post.details.split(',');
						let vArr = []
						arr.map(item => {
							let a1 = item.split('|')
							let obj = {
								url: a1[0],
								time: a1[1],
								playing: false,
							}
							vArr.push(obj)
						})
						post.voiceArr = vArr
					}
				})
			}
			postDetail.value = res.data
			QueryLike()
			loading.value = false
		})
	}

	const onReply = () => {
		if (aanLen.value < maxLen.value) {
			uni.navigateTo({
				url: `/pages/community/unscramble?id=${postId.value}`
			})
		} else {
			confirmDialogRef.value.open()
		}
	}

	/**
	 * @description 获取点赞状况
	 */
	function QueryLike() {
		uni.request({
			url: config.baseUrl + '/app/memberQuerycollect',
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			data: {
				'member.id': uni.getStorageSync('user').id,
				pst: 1,
				pid: postDetail.value.id
			}
		}).then(res => {
			let {
				data: resData
			} = res
			let {
				del
			} = resData
			_like.value = del == 0
		})

	}

	let likeAble = true
	/**
	 * @description 点赞
	 */
	function Like() {
		if (!likeAble) return
		likeAble = false
		uni.request({
			url: config.baseUrl + '/app/memberCollectSet',
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			data: {
				'member.id': uni.getStorageSync('user').id,
				pst: 1,
				pid: postDetail.value.id
			}
		}).then(res => {
			likeAble = true
			_like.value = !_like.value
		})
	}
</script>

<style lang="scss" scoped>
	.line {
		border-bottom: 2rpx dashed #ccc;
	}

	.btn-unscramble {
		position: fixed;
		right: 0;
		bottom: 100rpx;
		width: 162rpx;
		height: 84rpx;
		background: url('/static/community/bg_unscramble.png') no-repeat;
		background-size: cover;
	}

	.like {
		position: fixed;
		bottom: 30rpx;
		right: 30rpx;
		z-index: 999;
	}
</style>